import { Server } from "socket.io";
import { v4 as uuidv4 } from 'uuid'
import cache from '../../../cache.js'
import { proto2Obj } from '../../../util/index.js'
import { bot_login,bot_logout,bot_message } from "./handleEvent.js";

var io
const MAX_COUNT = 2
var roomNo = 1

// 获取io引用
function instanceIo(socket, nsp) {

  // 当前socket 
  const userId = socket.id
  socket.data.nickname = 'user_' + uuidv4()
  socket.data.enterTime = Date.now()
  const currNums = nsp.server.engine.clientsCount

  // io.engine.on("headers", (headers, req) => {
  //   headers["test"] = "789";
  // });
  const adminAdapter = nsp.adapter
  

  roomNo = 1
  socket.data.room = adminAdapter.nsp.name
  cache.setCache('socket', `${userId}`, { id: `${socket.id}`,value: socket.data })

  nsp.emit('enter' ,cache.getCache('socket',userId))

  socket.on('join',(id) => {
    socket.join(id)
    
  })

  socket.on('message', ({id,content}) => {
    
    nsp.to(id).emit('pri_message',content)
    
  })

  socket.on('bot_login', bot_login)
  socket.on('bot_logout',bot_logout)
  socket.on('bot_message',bot_message)
  return socket

}

/**
* SocketIO listen
*/
function handleIo() {
  const nsp = io.of('/admin')
  const dnsp = io.of('/rtc')

  dnsp.on('connection',(socket) => {
    

    const ins = instanceIo(socket,dnsp)


    ins.on('disconnect',bot_logout)
    
  })

  
  nsp.on('connection', (socket) => {
    

    const ins = instanceIo(socket,nsp)

    ins.on('disconnect', () => {
      cache.delCache('socket', ins.id)
      
    });
  })
}

// Socket init
function init(server) {
  io = new Server(server, {
    pingTimeout: 30000,
    maxHttpBufferSize: 1e8,
    transports: ['polling', 'websocket'],
    cors: {
      origin: "*",
      allowedHeaders: ["*"]
    }
  })
}
var sockets = (server) => {
  init(server)
  handleIo()
}


export default sockets